const { user_model, role_model } = require('../db/db')
const { code_status } = require('../utils/config.js')
const fastify = require('./server')
const dayjs = require('dayjs')
module.exports = {
    apis: [
        {
            method: 'GET',
            url: '/',
            preHandler: fastify.auth([
                fastify.verify,
            ]),
            handler: (req, res) => {
                res.send({ 'server': 'yes' })
            }
        },
        {
            method: 'POST',
            url: '/login',
            handler: async (req, res) => {
                if (req.body != undefined) {
                    if (req.body['username'] != undefined) {
                        const user = await user_model.findOne({ 'username': req.body['username'] }).exec()
                        //const user = await db.collection('admin_users').findOne({ 'username': req.body['username'] })

                        if (user) {
                            if (req.body['password'] === user['password']) {
                                user_model.findOneAndUpdate({ 'username': req.body['username'] }, { last_access: dayjs() })
                                const token = await fastify.jwt.sign(
                                    {
                                        _id: user['_id'],
                                        username: user['username'],
                                        phone: user['phone']
                                    }
                                )
                                res.send({
                                    statusCode: code_status.SUCCESS,
                                    message: "登陆成功",
                                    data: {
                                        access_token: token,
                                        exp: '-1'
                                    }
                                })
                            } else {
                                res.send({
                                    statusCode: code_status.FAIL,
                                    message: "用户密码错误",
                                    data: {}
                                })
                            }
                        } else {
                            res.send({
                                statusCode: code_status.FAIL,
                                message: "用户不存在",
                                data: {}
                            })
                        }
                    }
                    else if (req.body['phone'] != undefined) {
                        const user = await user_model.findOne({ 'phone': req.body['phone'] }).exec()
                        // const user = await db.collection('admin_users').findOne({ 'phone': req.body['phone'] })
                        if (user) {
                            if (req.body['password'] === user['password']) {
                                const c = user_model.findOneAndUpdate({ 'phone': req.body['phone'] }, { last_access: dayjs() }).exec()
                                console.log(c)
                                const token = await fastify.jwt.sign(
                                    {
                                        _id: user['_id'],
                                        username: user['username'],
                                        phone: user['phone']
                                    })
                                res.send({
                                    statusCode: code_status.SUCCESS,
                                    message: "登陆成功",
                                    data: {
                                        access_token: token,
                                        exp: '-1'
                                    }
                                })
                            } else {
                                res.send({
                                    statusCode: code_status.FAIL,
                                    message: "密码错误",
                                    data: {}
                                })
                            }
                        } else {
                            res.send({
                                statusCode: code_status.FAIL,
                                message: "电话号码不存在",
                                data: {}
                            })
                        }
                    } else {
                        res.send({
                            statusCode: code_status.FAIL,
                            message: "请输入用户名或者电话号码",
                            data: {}
                        })
                    }

                } else {
                    res.status(code_status.FAIL).send({
                        statusCode: code_status.FAIL,
                        message: "请传入用户名与密码",
                        data: {
                            // access_token:token,
                            // exp:'-1'
                        }
                    })
                }


            }
        },
        {
            method: 'POST',
            url: '/register',
            preHandler: fastify.auth([
                fastify.verify,
            ]),
            handler: async (req, res) => {
                let message = {}
                try {
                    message = await db.collection('admin_users').insertOne({
                        "username": req.body['username'],
                        "password": req.body['password'],
                        "phone": req.body['phone'],
                        "email": "admin@example.com",
                        "location": "New York City",
                        "title": "CTO",
                        "description": null,
                        "tags": null,
                        "avatar": null,
                        "theme": "auto",
                        "tfa_secret": null,
                        "status": "active",
                        "roles": null,
                        "token": null,
                        "last_access": "2021-02-05T10:18:13-05:00",
                        "last_page": "/settings/roles/653925a9-970e-487a-bfc0-ab6c96affcdc"
                    })
                }
                catch (e) {
                    if (e.name === 'MongoServerError') {
                        res.send({
                            statusCode: code_status.FAIL,
                            e: e.name + e.message,
                            message: '用户名有重复，请重新登陆'
                        })
                    } else {
                        res.send({
                            statusCode: code_status.FAIL,
                            e: e.name + e.message,
                            message: '请输入正确信息'
                        })
                    }
                }
                finally {
                    res.send({
                        statusCode: code_status.SUCCESS,
                        message
                    })
                }
            }
        },
        {
            method: 'GET',
            url: '/me',
            preHandler: fastify.auth([fastify.verify]),
            handler: async function get(req, res) {
                let jwt_info = this.jwt.decode(req.raw.headers['authorization'].slice(7))
                let all_info = await user_model.findById(jwt_info['_id'], { password: 0 }).populate('roles').exec()

                res.send({
                    statusCode: code_status.SUCCESS,
                    message: "查询成功！欢迎回来！",
                    data: {
                        jwt_info: jwt_info,
                        all_info: all_info
                    }
                })
            }
        },
        {
            method: 'GET',
            url: '/users',
            preHandler: fastify.auth([
                fastify.verify,
            ]),
            handler: async (req, res) => {
                let data = {}
                try {
                    data = await user_model.find({}, { password: 0 }).populate('roles')
                    data.forEach(e => e['password'] = '******')
                }
                catch (e) {
                    res.send({
                        statusCode: code_status.FAIL,
                        e: e.name,
                        message: e.message
                    })
                }
                finally {
                    res.send({
                        statusCode: code_status.SUCCESS,
                        data,
                        message: "查询成功"
                    })
                }
            }
        }
    ]
}